import { Strategy, ExtractJwt } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { UserService } from 'src/modules/user/user.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly configService: ConfigService,
    private userService: UserService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: 'hqh030201', // 建议使用环境变量
    });
  }

  /** token解析成功后通过sub（id）查询用户并返回 */
  async validate(payload: any) {
    // 获取用户ID和令牌签发时间
    const userId = payload.sub || payload.id;
    const tokenIssuedAt = payload.iat; // JWT标准字段：令牌签发时间

    // 检查用户令牌是否已被撤销（用户是否已退出）
    const isTokenRevoked = await this.userService.isTokenRevoked(
      userId,
      tokenIssuedAt,
    );

    if (isTokenRevoked) {
      throw new UnauthorizedException('您已退出登录，请重新登录');
    }
    return payload;
  }
}
